package org.jeecg.modules.xxgx.djgl.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.innerApi.common.requestDto.InvoiceParam;
import org.jeecg.modules.innerApi.common.requestDto.InvoicemxParam;
import org.jeecg.modules.innerApi.common.responseDto.InvoiceRtn;
import org.jeecg.modules.xxgx.common.enums.KpztEnum;
import org.jeecg.modules.xxgx.common.enums.TdyslxDmEnum;
import org.jeecg.modules.xxgx.djgl.entity.*;
import org.jeecg.modules.xxgx.djgl.enums.ZsfsEnum;
import org.jeecg.modules.xxgx.djgl.mapper.CsXxYkdjMapper;
import org.jeecg.modules.xxgx.djgl.mapper.CsXxYkdjmxMapper;
import org.jeecg.modules.xxgx.djgl.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 已开单据
 * @Author: jeecg-boot
 * @Date:   2023-08-18
 * @Version: V1.0
 */
@Service
public class CsXxYkdjServiceImpl extends ServiceImpl<CsXxYkdjMapper, CsXxYkdj> implements ICsXxYkdjService {

	@Autowired
	private CsXxYkdjMapper csXxYkdjMapper;
	@Autowired
	private CsXxYkdjmxMapper csXxYkdjmxMapper;
	@Autowired
	private ICsXxYkdjmxService csXxYkdjmxService;
	@Autowired
	private ICsXxDkdjService dkdjService;
	@Autowired
	private ICsXxDkdjmxService dkdjmxService;
	@Autowired
	private ICsXxDkdjExtService dkdjExtService;
	@Autowired
	private ICsXxDkdjCezsService dkdjCezsService;

	@Autowired
	private ICsXxYkdjExtService ykdjExtService;
	@Autowired
	private ICsXxYkdjCezsService ykdjCezsService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(CsXxYkdj csXxYkdj, List<CsXxYkdjmx> csXxYkdjmxList) {
		csXxYkdjMapper.insert(csXxYkdj);
		if(csXxYkdjmxList!=null && csXxYkdjmxList.size()>0) {
			for(CsXxYkdjmx entity:csXxYkdjmxList) {
				//外键设置
				entity.setFromid(csXxYkdj.getId());
				csXxYkdjmxMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(CsXxYkdj csXxYkdj,List<CsXxYkdjmx> csXxYkdjmxList) {
		csXxYkdjMapper.updateById(csXxYkdj);
		
		//1.先删除子表数据
		csXxYkdjmxMapper.deleteByMainId(csXxYkdj.getId());
		
		//2.子表数据重新插入
		if(csXxYkdjmxList!=null && csXxYkdjmxList.size()>0) {
			for(CsXxYkdjmx entity:csXxYkdjmxList) {
				//外键设置
				entity.setFromid(csXxYkdj.getId());
				csXxYkdjmxMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		csXxYkdjmxMapper.deleteByMainId(id);
		csXxYkdjMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			csXxYkdjmxMapper.deleteByMainId(id.toString());
			csXxYkdjMapper.deleteById(id);
		}
	}

	/**
	 * 根据待开单据开具结果，将待开单据转移到已开单据表中，并删除待开单据表中的单据信息
	 * @param invoiceParam 开票信息
	 * @param fpxxRtn   开票返回信息
	 * @param isDelDkdj   是否删除待开单据
	 */
	@Transactional
	public void saveYkdjByDkdjAndDelDkdj(InvoiceParam invoiceParam, InvoiceRtn fpxxRtn, Boolean isDelDkdj){
		String companyId = invoiceParam.getQyxx().getId();
		int tenantId = invoiceParam.getKpzd().getTenantId();
		CsXxYkdj ykdj=new CsXxYkdj();
		List<CsXxDkdjmx> csXxDkdjmxList = new ArrayList<>();
		//查询待开单据信息在表中是否存在，如存在则从待开单据中原样转存到已开单据中
		CsXxDkdj dkdj = dkdjService.getById(invoiceParam.getFpsqlsh());
		if(dkdj != null) {
			BeanUtils.copyProperties(dkdj,ykdj);
			csXxDkdjmxList = dkdjmxService.selectByMainId(dkdj.getId());
		} else {
			BeanUtils.copyProperties(invoiceParam,ykdj);

			//获取当前用户信息
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			String userName = "";
			if (user != null) {
				userName = user.getUsername();
			}

			ykdj.setId(invoiceParam.getFpsqlsh());
			ykdj.setCompanyId(companyId);
			ykdj.setSysOrgCode(invoiceParam.getBmdm());
			ykdj.setTenantId(tenantId);
			ykdj.setYhdm(userName);

			for(InvoicemxParam invoicemxParam : invoiceParam.getFpmxs()){
				//转到待开明细
				CsXxDkdjmx dkdjmx = new CsXxDkdjmx();
				dkdjmx.setCompanyId(companyId);
				BeanUtils.copyProperties(invoicemxParam, dkdjmx);
				csXxDkdjmxList.add(dkdjmx);
			}
		}

		InvoiceRtn.InvoiceRtnData rtnData = fpxxRtn.getData();
		//设置开票日期、开票状态
		ykdj.setKprq(rtnData.getKprq());
		ykdj.setFpdm(rtnData.getFpdm());
		ykdj.setFphm(rtnData.getFphm());
		ykdj.setKpzt(KpztEnum.ykp.getValue());
		//保存已开单据信息
		save(ykdj);

		List<CsXxYkdjmx> ykdjmxs=new ArrayList();
		csXxDkdjmxList.forEach(dkdjmx->{
			CsXxYkdjmx ykdjmx=new CsXxYkdjmx();
			BeanUtils.copyProperties(dkdjmx,ykdjmx);
			if(StringUtils.isEmpty(ykdjmx.getFromid())){
				ykdjmx.setFromid(ykdj.getId());
			}
			ykdjmxs.add(ykdjmx);
		});
		//保存已开单据明细
		csXxYkdjmxService.saveBatch(ykdjmxs);

		//保存扩展表信息(特定业务)
		if(dkdj != null) {
			CsXxDkdjExt csXxDkdjExt = dkdjExtService.getById(dkdj.getId());
			if(csXxDkdjExt != null) {
				CsXxYkdjExt csXxYkdjExt = new CsXxYkdjExt();
				BeanUtils.copyProperties(csXxDkdjExt, csXxYkdjExt);
				ykdjExtService.saveOrUpdate(csXxYkdjExt);
			}
		} else {
			CsXxYkdjExt csXxYkdjExt = new CsXxYkdjExt();
			csXxYkdjExt.setId(ykdj.getId());
			csXxYkdjExt.setFromid(ykdj.getId());
			csXxYkdjExt.setCompanyId(companyId);
			if(TdyslxDmEnum.JZFW.getValue().equals(invoiceParam.getTdyslxdm())){
				csXxYkdjExt.setTdywInfo(JSON.toJSONString(invoiceParam.getTdywJzfw()));
			} else if(TdyslxDmEnum.HWYSFW.getValue().equals(invoiceParam.getTdyslxdm())){
				csXxYkdjExt.setTdywInfo(JSON.toJSONString(invoiceParam.getTdywHwysfwList()));
			} else if(TdyslxDmEnum.BDCXS.getValue().equals(invoiceParam.getTdyslxdm())){
				csXxYkdjExt.setTdywInfo(JSON.toJSONString(invoiceParam.getTdywBdcxs()));
			} else if(TdyslxDmEnum.BDCJYZLFW.getValue().equals(invoiceParam.getTdyslxdm())){
				csXxYkdjExt.setTdywInfo(JSON.toJSONString(invoiceParam.getTdywBdcjyzlfw()));
			} else if(TdyslxDmEnum.LKYSFW.getValue().equals(invoiceParam.getTdyslxdm())){
				csXxYkdjExt.setTdywInfo(JSON.toJSONString(invoiceParam.getTdywLkysfwList()));
			}
			//附加要素保存
			if(invoiceParam.getFjysList() != null && invoiceParam.getFjysList().size()>0){
				csXxYkdjExt.setFjysInfo(JSON.toJSONString(invoiceParam.getFjysList()));
			}
			if(!StringUtils.isEmpty(csXxYkdjExt.getTdywInfo()) || !StringUtils.isEmpty(csXxYkdjExt.getFjysInfo())) {
				ykdjExtService.saveOrUpdate(csXxYkdjExt);
			}
		}

		//差额征收
		List<?> cezsList = new ArrayList<>();
		List<CsXxYkdjCezs> csXxYkdjCezsList = new ArrayList<>();
		if(dkdj != null) {
			cezsList = dkdjCezsService.lambdaQuery().eq(CsXxDkdjCezs::getFromid,dkdj.getId()).list();
		} else {
			if (!ZsfsEnum.PTZS.getValue().equals(invoiceParam.getZsfs())) {
				//保存差额征收信息
				cezsList = invoiceParam.getCezsList();
			}
		}
		if(cezsList != null && cezsList.size() > 0) {
			cezsList.forEach(cezs -> {
				CsXxYkdjCezs csXxYkdjCezs = new CsXxYkdjCezs();
				BeanUtils.copyProperties(cezs, csXxYkdjCezs);
				csXxYkdjCezs.setId(IdWorker.getIdStr());
				csXxYkdjCezs.setFromid(ykdj.getId());
				csXxYkdjCezs.setCompanyId(ykdj.getCompanyId());
				csXxYkdjCezsList.add(csXxYkdjCezs);
			});
			ykdjCezsService.saveBatch(csXxYkdjCezsList);
		}

		//删除待开单据信息
		if(isDelDkdj) {
			dkdjService.removeById(ykdj.getId());
			dkdjmxService.removeBatchByIds(csXxDkdjmxList);

			LambdaQueryWrapper<CsXxDkdjCezs> csXxDkdjCezsLambdaQueryWrapper = new LambdaQueryWrapper<>();
			csXxDkdjCezsLambdaQueryWrapper.eq(CsXxDkdjCezs::getFromid,ykdj.getId());
			dkdjCezsService.remove(csXxDkdjCezsLambdaQueryWrapper);

			LambdaQueryWrapper<CsXxDkdjExt> csXxDkdjExtLambdaQueryWrapper = new LambdaQueryWrapper<>();
			csXxDkdjExtLambdaQueryWrapper.eq(CsXxDkdjExt::getFromid,ykdj.getId());
			dkdjExtService.remove(csXxDkdjExtLambdaQueryWrapper);
		}
	}
	/**
	 * 分页查询已开单据列表
	 * @param page
	 * @param query
	 * @return
	 */
	public Page<CsXxYkdj> queryCsXxYkdjPageList(Page page,CsXxYkdj query){
		return csXxYkdjMapper.queryCsXxYkdjPageList(page,query);
	}
	
}
